package com.dachuang.canjiren.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dachuang.canjiren.entity.User;
import com.dachuang.canjiren.entity.UserQuery;
import com.dachuang.canjiren.mapper.UserMapper;
import com.dachuang.common.utils.R;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/pub")
public class LoginController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("need_login")
    public R needLogin() {

        return R.error("error:未登录或者登录失败");

    }


    @RequestMapping("not_permit")
    public R notPermit() {

        return R.error("error:未获得权限，或者权限不足");
    }

    /**
     * 登录接口
     *
     * @param userQuery
     * @param request
     * @param response
     * @return
     */
    @PostMapping("login")
    public R login(@RequestBody UserQuery userQuery, HttpServletRequest request, HttpServletResponse response) {
//        // 验证状态码
//        User users = userMapper.selectOne(new QueryWrapper<User>().eq("account",userQuery.getAccount()));
//        System.out.println(users);
//        if (users.getActive_status() == 0){
//            return R.error("error : 请前往注册邮箱激活");
//        }
        Subject subject = SecurityUtils.getSubject();
        Map<String, Object> info = new HashMap<>();
        try {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userQuery.getAccount(), userQuery.getPassword());


            subject.login(usernamePasswordToken);

            return R.ok("登录成功").put("session_id", subject.getSession().getId());

        } catch (Exception e) {
            e.printStackTrace();

            return R.error("error : 用户名或者密码错误");

        }


    }
}
